package org.vergil.core.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.vergil.core.dao.SsoUserMapper;
import org.vergil.core.dao.pojo.SsoUser;
import org.vergil.core.service.JwtService;
import org.vergil.core.service.UserService;
import org.vergil.dto.Jwt;
import org.vergil.dto.User;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * Created by vergil on 17-4-5.
 */
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private SsoUserMapper userMapper;
    @Autowired
    private JwtService jwtService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Long insert(User user) {
        return null;
    }

    @Override
    public int update(User user) {
        return 0;
    }

    @Override
    public int delete(Long userId) {
        return 0;
    }

    @Override
    public User getUser(Long userId) {
        return null;
    }

    @Override
    public User getUser(String username, String password) {
        return null;
    }

    @Override
    public List<User> getUsers(Map<String, Object> param) {
        return null;
    }

    @Override
    public String getUserToken(String username, String passwrod) {
        Optional<SsoUser> user = Optional.ofNullable(userMapper.selectUser(username, passwrod));
        Optional<String> result = user.map(value -> jwtService.LoginAndCreateJwt(value));
        return result.orElse(null);
    }

    @Override
    public Boolean logout(Jwt jwt) {
        if (redisTemplate.hasKey(jwt.getSignature())) {
            return false;
        }
        LocalDateTime expTime = LocalDateTime.parse(jwt.getPlayload().getExp());
        Long timeout = Duration.between(LocalDateTime.now(), expTime).toMillis();
        redisTemplate.opsForValue().set(jwt.getSignature(),jwt.getJwtContext(),timeout, TimeUnit.MILLISECONDS);
        return redisTemplate.hasKey(jwt.getSignature());
    }
}
